export default class ParamsUtil {
  // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  static addParams(url: string, params): string {
    let newUrl = url || '';
    Object.keys(params).forEach((key) => {
      if (params[key] === undefined || params[key] === null) {
        return;
      }
      if (newUrl.indexOf('?') > newUrl.indexOf('#')) {
        newUrl = `${newUrl}&${key}=${encodeURIComponent(params[key])}`;
      } else {
        newUrl = `${newUrl}?${key}=${encodeURIComponent(params[key])}`;
      }
    });
    return newUrl;
  }

  static getParams(url: string): { [key: string]: string | boolean } {
    const params = {};
    const search = url.split('?')[1];
    if (search) {
      const parts = search.split('&');
      for (let i = 0; i < parts.length; i++) {
        const nv = parts[i].split('=');
        if (nv[0]) {
          params[nv[0]] = nv[1] || true;
        }
      }
    }
    return params;
  }

  static removeParams(keyName: string, urlStr: string): string {
    const name = keyName.replace(/[\[\]]/g, '\\$&');
    const regex = new RegExp(`[?&]${name}(=([^&#]*(&|#|$))|&|#|$)`);
    return urlStr.replace(regex, (item) => {
      if (/^\?/.test(item)) {
        return '?';
      }
      if (/^&.+&$/.test(item)) {
        return '&';
      }
      if (/#$/.test(item)) {
        return '#';
      }
      return '';
    });
  }
}
